//
//  UIViewController+Swizzing.m
//  MMSwizzing_Example
//
//  Created by Mac on 2018/3/26.
//  Copyright © 2018年 CocoaPods. All rights reserved.
//

#import "UIViewController+Swizzing.h"
#import "SwizzingManager.h"
#import "Analytics.h"
#import <objc/runtime.h>
#import <JRSwizzle/JRSwizzle.h>

static NSString *const PageNameKey = @"PageId";

@implementation UIViewController (Swizzing)

+ (void)load {
    
    NSError *error = nil;
    NSError *disappearError = nil;
    [self jr_swizzleMethod:@selector(viewWillAppear:) withMethod:@selector(xl_swizzlingViewWillAppear:) error:&error];
    [self jr_swizzleMethod:@selector(viewWillDisappear:) withMethod:@selector(xl_swizzlingViewWillDisAppear:) error:&disappearError];
    if (error != nil || disappearError != nil) {
        NSLog(@"Swizzing Error = %@ %@", error, disappearError);
        return;
    }
}

- (void)xl_swizzlingViewWillAppear:(BOOL)animated {
    [self sendBeginUBTAction];
    [self xl_swizzlingViewWillAppear:animated];
}

- (void)xl_swizzlingViewWillDisAppear:(BOOL)animated {
    [self sendEndUBTAction];
    [self xl_swizzlingViewWillDisAppear:animated];
}

- (void)sendBeginUBTAction {
    NSString *pageName = [self getPageName];
    if (pageName != nil && ![pageName isKindOfClass:[NSNull class]]) {
        [Analytics beginPage:pageName];
    }
}

- (void)sendEndUBTAction {
    NSString *pageName = [self getPageName];
    if (pageName != nil && ![pageName isKindOfClass:[NSNull class]]) {
        [Analytics endPage:pageName];
    }
}

- (NSString *)getPageName {
    
    NSString *classNameWithSpaceName = NSStringFromClass([self class]);
    if ([classNameWithSpaceName componentsSeparatedByString:@"."].count < 2) {
        return nil;
    }
    SwizzingManager *manager = [SwizzingManager sharedManager];
    if (manager.swizzingConfigDictinary == nil) {
        
        BOOL asset = NO;
        
        #if RELEASE
                asset = NO;
        #elif DEBUG
                asset = YES;
        #elif DEV
                asset = YES;
        #elif TEST
                asset = YES;
        #endif
        
        NSAssert(asset, @"请加载埋点统计对应的Plist配置文件");
    }
    NSString *className = [classNameWithSpaceName componentsSeparatedByString:@"."][1];
    return manager.swizzingConfigDictinary[className];
    
}

@end
